<style scoped>
.ivu-form-item {
    margin-bottom: 5px;
}
.demo-upload-list{
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 4px;
    }
    .demo-upload-list img{
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>
<template>
  <div>
    <Card>
      <div  class="search-con search-con-top">
        <Button style="margin-right: 10px;" type="primary" @click="addOrUpdate = true">添加</Button>
        <Button style="margin-right: 10px;" type="primary" @click="exportExcel">导出为Csv文件</Button>
        <Select v-model="searchKey" class="search-col" placeholder="请选择检索项">
          <Option v-for="item in columns" v-if="item.key !== 'handle'" :value="item.key" :key="item.key">{{ item.title }}</Option>
        </Select>
        <Input clearable placeholder="输入关键字搜索" class="search-input" v-model="searchValue"/>
        <Button @click="handleSearch" class="search-btn" type="primary"><Icon type="search"/>&nbsp;&nbsp;搜索</Button>
      </div>
      
      <tables :height="innerHeight - 250" ref="tables" search-place="top" v-model="tableData" :columns="columns" :loading="tabLoading"/>
      <div style="margin: 10px;overflow: hidden">
        <div style="float: right;">
            <Page :total="total" size="small" show-elevator show-sizer @on-change="changePage" @on-page-size-change="pageSizeChange"/>
        </div>
      </div>
    </Card>
    <Modal v-model="addOrUpdate" :title="modelTitle" @on-ok="ok" @on-cancel="cancel" :mask-closable="false" width="1000">
        <Form ref="addFrom" :model="addFrom" :label-width="100">
            <Row>
                <Col span="8">
                    <FormItem label="机构编码" prop="prvCode" :rules="{required: true, message: '请填写机构编码', trigger: 'blur'}">
                        <Input v-model="addFrom.prvCode" placeholder="请填写机构编码"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="机构名称" prop="prvName" :rules="{required: true, message: '请填写机构名称', trigger: 'blur'}">
                        <Input v-model="addFrom.prvName" placeholder="填写机构名称"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="机构类型" prop="provTypeId" :rules="{required: true, message: '选择机构类型', trigger: 'blur'}">
                        <Select v-model="addFrom.provTypeId" placeholder="选择机构类型" @on-change="provTypeChange">
                            <Option v-for="item in provTypeList" :value="item.provTypeId" :key="item.provTypeId">{{ item.provTypeName }}</Option>
                        </Select>
                    </FormItem>
                </Col>
                <Col span="24">
                    <FormItem label="机构描述" prop="机构描述" :rules="{required: true, message: '请填写机构描述', trigger: 'blur'}">
                        <Input v-model="addFrom.prvDesc" placeholder="请填写机构描述"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="地址" prop="addrDetail" :rules="{required: true, message: '请填写地址', trigger: 'blur'}">
                        <Input v-model="addFrom.addrDetail" placeholder="填写地址">
                          <Poptip title="选择标记地址" slot="append" @on-popper-show="addrShow">
                              <Icon type="ios-pin" />
                              <div  slot="content" >
                                  <div style="width:500px;">地址：{{addFrom.addrDetail}} 坐标X：{{addFrom.posX}} 坐标Y：{{addFrom.posY}} </div>
                                  <div>
                                    <Input v-model="mapaddress">
                                        <Button slot="append" icon="ios-search" @click="codeAddress"></Button>
                                    </Input>
                                  </div>
                                  <div id="mmap" style="width:500px;height:500px"></div>
                              </div>
                          </Poptip>
                        </Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="所属街道" prop="attribute10" >
                        <Select v-model="addFrom.attribute10" >
                            <Option v-for="item in streetList" :value="item.addrId+''" :key="item.addrId+''" >{{ item.addrName }}</Option>
                        </Select>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="坐标X" prop="posX" >
                        <Input v-model="addFrom.posX" readonly></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="坐标Y" prop="posY" >
                        <Input v-model="addFrom.posY" readonly></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="电话" prop="mobile" :rules="{required: true, message: '请填写电话', trigger: 'blur'}">
                        <Input v-model="addFrom.mobile" placeholder="请填写电话"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="机构图标" prop="attribute1" :rules="{required: true, message: '请上传图标', trigger: 'blur'}">
                        <Input v-model="addFrom.attribute1"   placeholder="请上传图标">
                            <Upload slot="append" :show-upload-list="false" :data="{uploadType:'org',resultType:''}" :format="['jpg','jpeg','png']" :on-success="handleSuccess" :on-error="handleError" action="https://www.dxbeibei.com/wx.minproject.xiong.application/file/comm/msg/fileUpload.do">
                              <Button icon="ios-cloud-upload-outline"></Button>
                            </Upload>
                        </Input>
                    </FormItem>
                </Col>
                <Col span="24">
                    <FormItem label="展示图片" prop="pic" >
                        <div class="demo-upload-list" v-for="item in pic.uploadList">
                            <template v-if="item.status === 'finished'">
                                <img :src="item.url">
                                <div class="demo-upload-list-cover">
                                    <Icon type="ios-eye-outline" @click.native="handleView(item.name)"></Icon>
                                    <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                                </div>
                            </template>
                            <template v-else>
                                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                            </template>
                        </div>
                        <Upload
                            ref="upload"
                            :show-upload-list="false"
                            :default-file-list="pic.defaultList"
                            :on-success="handleSuccess2"
                            :data="{uploadType:'org',resultType:''}"
                            :format="['jpg','jpeg','png']"
                            :max-size="2048"
                            multiple
                            type="drag"
                            action="https://www.dxbeibei.com/wx.minproject.xiong.application/file/comm/msg/fileUpload.do"
                            style="display: inline-block;width:58px;">
                            <div style="width: 58px;height:58px;line-height: 58px;">
                                <Icon type="ios-camera" size="20"></Icon>
                            </div>
                        </Upload>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="点赞数" prop="thumbsNumber">
                        <Input v-model="addFrom.thumbsNumber"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="评分" prop="score">
                        <Input v-model="addFrom.score"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="评分数量" prop="scoreNum">
                        <Input v-model="addFrom.scoreNum"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="收藏数量" prop="collected">
                        <Input v-model="addFrom.collected"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="最大金额" prop="maxPrice">
                        <Input v-model="addFrom.maxPrice"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="最小金额" prop="minPrice">
                        <Input v-model="addFrom.minPrice"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="营业时间" prop="attribute2">
                        <Input v-model="addFrom.attribute2"></Input>
                    </FormItem>
                </Col>
                <Col span="16">
                    <FormItem label="商品标签" prop="prodLabel">
                        <Input v-model="addFrom.prodLabel"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="pc软件" prop="downForPc">
                        <Input v-model="addFrom.downForPc"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="pc下载数量" prop="countForPc">
                        <Input v-model="addFrom.countForPc"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="安卓软件" prop="downForAndroid">
                        <Input v-model="addFrom.downForAndroid"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="安卓下载数量" prop="countForAndroid">
                        <Input v-model="addFrom.countForAndroid"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="ios软件" prop="downForIos">
                        <Input v-model="addFrom.downForIos"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="ios下载数量" prop="countForIos">
                        <Input v-model="addFrom.countForIos"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="收藏数" prop="attribute3">
                        <Input v-model="addFrom.attribute3"></Input>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="类型标示" prop="attribute4">
                        <Input v-model="addFrom.attribute4"></Input>
                    </FormItem>
                </Col>
            </Row>
        </Form>
        <Modal title="View Image" v-model="pic.visible">
            <img :src="'https://www.dxbeibei.com/wx.minproject.xiong.html/' + pic.imgName" v-if="pic.visible" style="width: 100%">
        </Modal>
    </Modal>
  </div>
  
</template>

<script>
import Tables from '_c/tables'
import { tablePublicRequest } from '@/api/data'
import { TMap } from '@/libs/TMap'

export default {
  name: 'tables_page',
  components: {
    Tables
  },
  data () {
    return {
      actionUrl:{
        "BATCH":"smc/base/SystemProviderUser/saveSystemProviderUser.json",
  		  "QRY":"smc/base/SystemProviderUser/querySystemProviderUser.json",
  		  "ADD":"smc/base/SystemProviderUser/addSystemProviderUser.do",
  		  "DEL":"smc/base/SystemProviderUser/delSystemProviderUser.do",
  		  "UPD":"smc/base/SystemProviderUser/updSystemProviderUser.do",
  		  "LKUP":"smc/base/SystemProviderUser/lookupSystemProviderUser.json",
  		  "LST":"smc/base/SystemProviderUser/listSystemProviderUser.json",
          "FIND":"smc/base/SystemProviderUser/findSystemProviderUser.json",
          "TYPELST":"smc/base/SystemProviderType/listSystemProviderType.json",
      },    
      innerHeight:document.body.clientHeight,
      pic:{
        defaultList: [],
        imgName: '',
        visible: false,
        uploadList: []
      },
      addOrUpdate: false,
      modelTitle:"新增",
      searchKey:"",
      searchValue:"",
      mapaddress:"",
      page:1,
      pageSize:10,
      total:0,
      search:{},
      tabLoading:true,
      addFrom:{
        attribute1:""
      },
      streetList:[],
      provTypeList:[],
      geocoder:"",
      columns: [
        {title: '机构编码', key: 'prvCode', sortable: true,width:120},
        {title: '机构名称', key: 'prvName', sortable: true,width:120},
        {title: '机构描述', key: 'prvDesc', sortable: true,width:120},
        {title: '机构类型', key: 'provtypeid_provTypeName', sortable: true,width:120},
        {title: '移动电话', key: 'mobile', sortable: true,width:120},
        {title: '地址', key: 'addrDetail', sortable: true,width:100},
        {title: '坐标X', key: 'posX', sortable: true,width:100},
        {title: '坐标Y', key: 'posY', sortable: true,width:100},
        {title: '机构图标', key: 'attribute1',sortable: true,width:120,render: (h, params) => {
            return h('div', {
              attrs: {
                style: 'width: 40px;height: 40px;'
              },
            }, [
                h('img', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  attrs: {
                    src: `https://www.dxbeibei.com/wx.minproject.xiong.html/${params.row.attribute1}`, style: 'width: 40px;height: 40px;border-radius: 2px;'
                  },
                  style: {
                  },
                }),
              ]);
          }},
        {title: '点赞数', key: 'thumbsNumber', sortable: true,width:120},
        {title: '评分', key: 'score', sortable: true,width:100},
        {title: '评分数量', key: 'scoreNum', sortable: true,width:120},
        {title: '收藏数量', key: 'collected', sortable: true,width:120},
        {title: '最大金额', key: 'maxPrice', sortable: true,width:120},
        {title: '最小金额', key: 'minPrice', sortable: true,width:120},
        {title: '营业时间', key: 'attribute2', sortable: true,width:120},
        {title: '商品标签', key: 'prodLabel', sortable: true,width:120},
        {title: 'pc软件', key: 'downForPc', sortable: true,width:120},
        {title: 'pc下载数量', key: 'countForPc', sortable: true,width:120},
        {title: '安卓软件', key: 'downForAndroid', sortable: true,width:120},
        {title: '安卓下载数量', key: 'countForAndroid', sortable: true,width:120},
        {title: 'ios软件', key: 'downForIos', sortable: true,width:120},
        {title: 'ios下载数量', key: 'countForIos', sortable: true,width:120},
        {
          title: '操作',
          key: 'handle',
          fixed:'left',
          width:80,
          button: [
            (h, params, vm) => {
              return h('Button', {
                  props: {
                    type: 'text',
                    ghost: true
                  },
                  attrs:{
                    style:"padding: 5px 0;"
                  },
                  on: {
                    'click': () => {
                      tablePublicRequest(this.actionUrl.FIND,{"id":params.row.prvId}).then(res => {
                        let data = res.data;
                        if(data.success){
                            var d = data.data || {};
                            if(d.attribute9){
                                tablePublicRequest(`smc/base/SystemAddress/querySystemAddress.json?page=1&pagesize=1000&$parentId=${d.attribute9}`,{}).then(res2 => {
                                    var data2 = res2.data.data;
                                    this.streetList = data2.rows;
                                    this.findPrv(d);
                                })
                            }else{
                                this.findPrv(d);
                            }
                        }
                      })
                    }
                  }
                }, [
                  h('Icon', {
                    props: {
                      type: 'ios-create',
                      size: 18,
                      color: '#000000'
                    }
                  })
              ])
            },
            (h, params, vm) => {
              return h('Poptip', {
                props: {
                  confirm: true,
                  title: '你确定要删除吗?',
                  transfer:true
                },
                on: {
                  'on-ok': () => {
                    tablePublicRequest(this.actionUrl.DEL,{"id":params.row.prvId}).then(res => {
                      let data = res.data;
                      if(data.success){
                        this.$Message.info('删除成功！');
                        this.handleSearch();
                        this.pic={
                            defaultList: [],
                            imgName: '',
                            visible: false,
                            uploadList: []
                        }
                      }
                    })
                  }
                }
              }, [
                h('Button', {
                  props: {
                    type: 'text',
                    ghost: true
                  },
                  attrs:{
                    style:"padding: 5px 0;"
                  },
                }, [
                  h('Icon', {
                    props: {
                      type: 'md-trash',
                      size: 18,
                      color: '#000000'
                    }
                  })
                ])
              ])
            }
          ]
        }
      ],
      tableData: []
    }
  },
  methods: {
    findPrv(data){
        console.log(data);
        this.addFrom = data || {};
        this.addOrUpdate = true;
        var zpic = this.addFrom.pic;
        if(zpic && zpic.length > 0){
            let zpics = zpic.split(",");
            let dlist = [];
            for(var i=0;i<zpics.length;i++){
                dlist.push({status:'finished',name:zpics[i],url: `https://www.dxbeibei.com/wx.minproject.xiong.html/${zpics[i]}`});
            }
            this.$refs.upload.fileList = dlist;
            this.pic={
                defaultList: dlist,
                imgName: '',
                visible: false,
                uploadList: dlist
            }
        }
        this.addFrom.attribute10 = data.attribute10;
    },
    exportExcel () {
      this.$refs.tables.exportCsv({
        filename: `table-${(new Date()).valueOf()}.csv`
      })
    },
    ok () {
      delete this.addFrom.createdAt;
      delete this.addFrom.lastedUpdAt;
      let url = this.addFrom.prvId?this.actionUrl.UPD:this.actionUrl.ADD;
      this.modelTitle = this.addFrom.prvId?"修改":"新增";
      let pics = [];
      for(var i=0;i<this.pic.uploadList.length;i++){
            pics.push(this.pic.uploadList[i].name);
      }
      this.addFrom.pic = pics.toString();
      tablePublicRequest(url,this.addFrom).then(res => {
        let data = res.data;
        if(data.success){
          this.$Message.info(`${this.modelTitle}成功！`);
          this.handleSearch();
          this.addFrom = {attribute1:""};
          this.pic={
            defaultList: [],
            imgName: '',
            visible: false,
            uploadList: []
          }
        }
      })
    },
    cancel () {
        this.addFrom = {attribute1:""};
        this.pic={
            defaultList: [],
            imgName: '',
            visible: false,
            uploadList: []
        }
    },
    changePage (data) {
      this.page = data;
      this.handleSearch();
    },
    pageSizeChange(data){
      this.pageSize = data;
      this.handleSearch();
    },
    handleSearch(){
      this.search = {page: this.page,pagesize: this.pageSize};
      this.search.searchRules=`[{"op":"contains","field":"${this.searchKey}","value":"${this.searchValue}","type":"text"}]`;
      this.setTableData(this.search);
    },
    setTableData(params){
    this.tabLoading=true;
      tablePublicRequest(this.actionUrl.QRY,params).then(res => {
        let data = res.data;
        if(data.success){
          let tdata = data.data;
          this.total = tdata.total;
          this.tabLoading=false;
          this.tableData = tdata.rows||[];
        }
      })
    },
    handleSuccess(res, file){
      this.$Message.info(res.msg);
      this.addFrom.attribute1 = res.path;
    },
    handleError(res, file){
      this.$Message.info(res.msg);
    },
    handleView (name) {
        this.pic.imgName = name;
        this.pic.visible = true;
    },
    handleRemove (file) {
        let k=-1;
        for(var i=0;i<this.pic.uploadList.length;i++){
            if(file.name == this.pic.uploadList[i].name){
                k = i;
                break;
            }
        }
        this.pic.uploadList.splice(k, 1);

        const fileList = this.$refs.upload.fileList;
        this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
    },
    handleSuccess2 (res, file) {
      this.$Message.info(res.msg);
        
        this.pic.uploadList.push({status:'finished',name:res.path,url: `https://www.dxbeibei.com/wx.minproject.xiong.html/${res.path}`});
        file.url = `https://www.dxbeibei.com/wx.minproject.xiong.html/${res.path}`;
        file.name = res.path;
    },
    codeAddress(){
        this.geocoder.getLocation(this.mapaddress);
    },
    addrShow(){
        this.geocoder.getLocation(this.addFrom.addrDetail);
    },
    provTypeChange(val){
        for(var i=0;i<this.provTypeList.length;i++){
            var item = this.provTypeList[i];
            if(item.provTypeId == val){
                this.addFrom.attribute4 = item.attribute1;
            }
        }
    }
  },
  mounted () {
    this.setTableData({page: this.page,pagesize: this.pageSize});
    // this.pic.uploadList = this.$refs.upload.fileList;
    tablePublicRequest(this.actionUrl.TYPELST,{}).then(res => {
        let data = res.data;
        if(data.success){
          this.provTypeList = data.data;
        }
    })
    let selt = this;
    TMap().then(qq => {
        var map = new qq.maps.Map(document.getElementById("mmap"), {
            // 地图的中心地理坐标。
            center: new qq.maps.LatLng(39.916527, 116.397128),
              zoom: 15
        });
        var markersArray = [];
        selt.geocoder = new qq.maps.Geocoder({
            complete : function(result){
                if (markersArray) {
                    for (var i in markersArray) {
                        markersArray[i].setMap(null);
                    }
                }
                map.setCenter(result.detail.location);
                var marker = new qq.maps.Marker({
                    map:map,
                    position: result.detail.location
                });
                markersArray.push(marker);
                console.log(result.detail);
                let location = result.detail.location;
                let address = result.detail.address;
                let city = result.detail.addressComponents.city;
                let street = result.detail.addressComponents.street;
                let town = result.detail.addressComponents.district;
                var len = city.length
                var last = city.charAt(len - 1)
                if (last === '市') {
                      city = city.slice(0, -1)
                  }
                selt.addFrom = Object.assign({},selt.addFrom,{addrDetail:address+street,posX:location.lat,posY:location.lng,attribute8:city});
                
                tablePublicRequest(`smc/base/SystemAddress/querySystemAddress.json?page=1&pagesize=1000&$sid=3&$parentid_addrName-contains=${result.detail.addressComponents.city}`,{}).then(res => {
                    var data = res.data.data;
                    var rows = data.rows;
                    for(var i=0;i<rows.length;i++){
                        var row = rows[i];
                        if(row.addrName == town){
                            selt.addFrom.attribute9=row.addrId;
                            tablePublicRequest(`smc/base/SystemAddress/querySystemAddress.json?page=1&pagesize=1000&$parentId=${row.addrId}`,{}).then(res2 => {
                                var data2 = res2.data.data;
                                selt.streetList = data2.rows;
                            })
                        }
                    }
                })
            }
        });
        //添加监听事件
        qq.maps.event.addListener(map, 'click', function(e,b) {
            var latLng = new qq.maps.LatLng(e.latLng.lat, e.latLng.lng);
            //调用获取位置方法
            selt.geocoder.getAddress(latLng);
        });
    });
    
  }
}
</script>


